package kr.co.handysoft.smartPolice.server.handler.info;

import kr.co.handysoft.common.registry.SmartPoliceRegistry;
import net.sf.json.JSONObject;

import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

public class ExitClientHandler implements InfoServerHandler {

	private String kor;
	private String zoneKor;
	private String port;

	@Override
	public JSONObject invoke(String cmd) {
		JSONObject exitJSON = JSONObject.fromObject(cmd);
		kor = exitJSON.getString("kor");
		zoneKor = exitJSON.getString("zoneKor");
		port = exitJSON.getString("port");
		
		final Tree tree = (Tree)SmartPoliceRegistry.getReceiverTree();
		if (!tree.isDisposed()){
			tree.getDisplay().asyncExec(new Runnable() {
				
				@Override
				public void run() {
					TreeItem[] itemArray = tree.getItems();
					for (TreeItem item : itemArray){
						String portName = (String)item.getData("name");
						if (portName.equals(port)){
							findKor(item);
							break;
						}
					}
				}
			});
		}
		
		return new JSONObject();
	}

	private void findKor(TreeItem tgrItem) {
		TreeItem[] itemArray = tgrItem.getItems();
		
		for (TreeItem item : itemArray){
			
			String korName = (String)item.getData("name");
			System.out.println("kor Name : " + korName + "," + kor);
			if (korName.equals(kor)){
				findZoneKor(item);
				break;
			}
			
		}
	}

	private void findZoneKor(TreeItem tgrItem) {
		TreeItem[] itemArray = tgrItem.getItems();
		
		for (TreeItem item : itemArray){
			
			String zoneKorName = (String)item.getData("name");
			System.out.println("zoneKor Name : " + zoneKorName + "," + zoneKor);
			if (zoneKorName.equals(zoneKor)){
				item.dispose();
				break;
			}
			
		}
	}

}
